import express from "express";
import { tokenv, tokens, passwordEncrypt, passwordCompare } from "./encrypt.js";
import DBserve from "./nedb.js";
const router = express.Router();
import path from "path";
import fs from "fs";
import department from "./router/department.js";
import user from "./router/user.js";
import m3u8 from "./router/m3u8.js";
import vehicle from "./router/vehicle.js";
import report from "./router/report.js";
import calendar from "./router/calendar.js";
import dispatch from "./router/dispatch.js";
const base_url = "";
router.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With,myToken");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", " 3.2.1");
  res.header("Cache-Control", "no-store");
  res.header("Content-Type", "application/json;charset=utf-8");
  let white = ["/login", "/m3u8"];
  // console.log(req.originalUrl);
  // return res.send(req);
  if (white.includes(req.originalUrl)) {
    return next();
  }
  if (
    !tokenv(req.headers.authorization) ||
    tokenv(req.headers.authorization).code
  ) {
    return res.json(tokenv(req.headers.authorization));
  }
  next();
});
// 部门
department(router, DBserve);
// 人员
user(router, DBserve);
// m3u8
m3u8(router, DBserve);
// 车辆
vehicle(router, DBserve);
// 报表
report(router, DBserve);
// 日历
calendar(router, DBserve);
// 车辆调度
dispatch(router, DBserve);
// 上传文件
router.post("/upload", (req, res) => {
  let oldName, newName;
  try {
    oldName = req.files[0].path;
    newName = req.files[0].path + path.parse(req.files[0].originalname).ext;
    fs.renameSync(oldName, newName);
    // console.log(oldName, newName);
    let url =
      "/upload/" +
      req.files[0].filename +
      path.parse(req.files[0].originalname).ext;
    res.send({
      code: 200,
      message: "上传成功",
      url: base_url + url,
    });
    setTimeout(() => {}, 1000);
  } catch (error) {
    // console.log(error);
    res.send({ code: 400, message: "上传失败", error });
    fs.unlinkSync(newName);
  }
});
export default router;
